<template>
  <div class="table-page">
    <a-form
      label-align="right"
      layout="inline"
      auto-label-width
      :model="listParams"
      size="small"
      class="form mt-10 mb-20"
    >
      <a-form-item field="sourceChatroomId">
        <a-select
          v-model="listParams.sourceChatroomId"
          class="w-70n"
          placeholder="选择源头群"
          @change="changeCurrent(1)"
        >
          <a-option value="" label="全部源头群"></a-option>
          <a-option
            v-for="item in sourceList"
            :key="item.sourceChatRoomId"
            :value="item.sourceChatRoomId"
            :label="item.name"
          ></a-option>
        </a-select>
      </a-form-item>
      <a-form-item field="platformId">
        <a-select v-model="listParams.platformId" class="w-50n" placeholder="选择平台" @change="changeCurrent(1)">
          <a-option value="" label="全部平台"></a-option>
          <a-option
            v-for="item in platformList"
            :key="item.sourceType"
            :value="item.sourceType"
            :label="item.title"
          ></a-option>
        </a-select>
      </a-form-item>
      <a-form-item field="startAt" label="统计日期">
        <ms-date
          v-model:start="listParams.startAt"
          :disabledDate="
            (current) =>
              dayjs(current).isAfter(dayjs().endOf('date')) ||
              dayjs(current).isBefore(dayjs('2023-09-07').startOf('date'))
          "
          v-model:end="listParams.endAt"
          :showQuick="true"
          @dateChange="getTableData"
        ></ms-date>
      </a-form-item>
    </a-form>
    <GiTable
      row-key="id"
      ref="tt"
      id="sourceChatRoomGoodsRankData"
      v-model:columns="columns"
      :loading="loading"
      :data="tableData"
      @sorter-change="onSorterChange"
      :scroll="{ x: '100%', y: '100%', minWidth: 1000 }"
      :pagination="pagination"
      @refresh="getTableData"
    >
      <template #info="{ record }">
        <template v-if="record.name">
          <div class="flex">
            <a-image width="70" height="70" class="mr-10 cursor-pointer" :src="record.goodsImg" />
            <div class="flex-col m-relative flex-1 overflow-hidden">
              <div style="min-height: 22px" class="my-2 line-h-24 text-overflow-2">
                <div class="m-absolute t-0 l-0" v-if="record.platformName">
                  <a-tag color="red">{{ record.platformName }}</a-tag>
                </div>
                <div
                  :style="{
                    textIndent: `${record.platformName ? record.platformName.length * 14 + 16 : 0}px`
                  }"
                >
                  <a-tooltip :content="record.goodsTitle">
                    <span>{{ record.goodsTitle }}</span>
                  </a-tooltip>
                </div>
              </div>
              <div class="flex flex-a-c my-2">
                <span class="textd43030 text-size-14 font-bold"
                  ><span v-if="record.goodsPrice">￥{{ record.goodsPrice }}</span>
                </span>
              </div>
            </div>
          </div>
        </template>
        <template v-else>
          <div>--</div>
        </template>
      </template>
      <template #source="{ record }">
        <template v-if="!record.name">
          <span>{{ record.sourceChatRoomName }}</span>
        </template>
        <template v-else>
          <a-button type="text" size="small" @click="onMore(record.id, !record.isOpen)">
            {{ record.isOpen ? '收起' : '查看各源头数据' }}
          </a-button>
        </template>
      </template>
      <template #action="{ record }">
        <a-button type="text" size="small" @click="getUrl(record.goodsId, record.platformId)"> 复制链接 </a-button>
      </template>
    </GiTable>
  </div>
</template>

<script setup>
import dayjs from 'dayjs'
import { useSource, usePlatform } from '@/hooks/app'
import { usePagination } from '@/hooks'
import { sourceChatRoomGoodsRankData, getTargetUrl } from '@/apis'
import { deleteEmpty, copyText } from '@/utils/common'

defineOptions({ name: 'sourceChatRoomGoodsRankData' })
const tableData = ref([])
const loading = ref(false)
const tt = ref()
const { pagination, setTotal } = usePagination(() => getTableData(), { defaultPageSize: 20 })

// 公共参数
const listParams = reactive({
  startAt: dayjs().subtract(7, 'day').startOf('day').format('YYYY-MM-DD HH:mm:ss'),
  endAt: dayjs().subtract(1, 'day').endOf('day').format('YYYY-MM-DD HH:mm:ss'),
  sourceChatroomId: undefined,
  page: 1,
  platformId: undefined
})

const columns = ref([
  {
    title: '商品信息',
    width: 400,
    slotName: 'info'
  },
  {
    title: '源头群名称',
    width: 200,
    dataIndex: 'sourceChatroomName'
  },
  {
    title: '查看各源头数据',
    width: 200,
    slotName: 'source'
  },
  {
    title: '出单量',
    width: 100,
    align: 'center',
    dataIndex: 'totalOrderCount',
    sortable: {
      sortDirections: ['ascend', 'descend']
    }
  },
  {
    title: '总GMV',
    width: 100,
    align: 'center',
    dataIndex: 'totalGmv',
    sortable: {
      sortDirections: ['ascend', 'descend']
    }
  },
  {
    title: '总佣金',
    width: 100,
    align: 'center',
    dataIndex: 'totalCommission',
    sortable: {
      sortDirections: ['ascend', 'descend']
    }
  },
  {
    title: '操作',
    width: 100,
    slotName: 'action',
    align: 'center'
  }
])

// 获取源头群
const { sourceList, getSourceList } = useSource()
getSourceList()

// 获取平台
const { platformList, getPlatformList } = usePlatform()
getPlatformList()

// 获取链接
const getUrl = async (goodsId, sourceType) => {
  const res = await getTargetUrl({ inviteCode: 5368240, goodsId, sourceType })
  copyText(res.data.kl)
}

// 获取头部信息
const getTableData = async () => {
  try {
    loading.value = true
    listParams.page = pagination.current
    const res = await sourceChatRoomGoodsRankData(deleteEmpty({ ...listParams }))
    tableData.value = res.data.map((item, index) => {
      return {
        ...item,
        id: index + 600,
        children: item.sourceChatroomInfo,
        name: item.sourceChatroomName,
        isOpen: false
      }
    })
    setTotal(500)
  } finally {
    loading.value = false
  }
}
getTableData()

// 表格页码改变
const changeCurrent = (e) => {
  pagination.current = listParams.page = e
  getTableData()
}

//升降序发生改变
const onSorterChange = (dataIndex, direction) => {
  listParams.orderBy = direction ? (direction === 'ascend' ? 'asc' : 'desc') : undefined
  listParams.sort = listParams.orderBy ? dataIndex : undefined
  changeCurrent(1)
}

//点击展开更多
const onMore = (id, type) => {
  if (type) {
    tableData.value.forEach((item) => {
      item.isOpen = false
    })
    tt.value.tableRef.expandAll(false)
  }
  tt.value.tableRef.expand(id, type)
  const index = tableData.value.findIndex((item) => {
    return item.id === id
  })
  tableData.value[index].isOpen = type
}
</script>

<style lang="scss" scoped>
.table-page {
  height: 100%;
  overflow: hidden;
  margin: $margin;
  background: var(--color-bg-1);
  padding: $padding;
  box-sizing: border-box;
  display: flex;
  flex-direction: column;
  .form {
    :deep(.arco-form-item) {
      margin-bottom: 10px;
    }
  }
  :deep(.arco-table-cell-inline-icon) {
    display: none;
  }
}
</style>
